﻿using Microsoft.Win32;
using ShengYueWorkShop.BLL.MemoryProcessing;
using ShengYueWorkShop.BLL.PublicHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ShengYueWorkShop.Client
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// 时间线程，周期进行的时间
        /// </summary>
        private System.Timers.Timer _FTimer { get; set; }
        /// <summary>
        /// 用来对运行时长计时，同时也能看程序有没有死掉
        /// </summary>
        private Timer _StarTimer { get; set; } = new Timer();
        /// <summary>
        /// 数据模型
        /// </summary>
        private BLL.DataModel.WS_FtpServer _DataModel { get; set; } = new BLL.DataModel.WS_FtpServer();
        /// 开始运行的时间
        /// </summary>
        private DateTime _YunXinDtime { get; set; }
        /// <summary>
        /// sql帮助类
        /// </summary>
        private SqlHelper _SqlHelper { get; set; } = new SqlHelper();

        public Form1()
        {
            InitializeComponent();
            EventBinding();
        }
        #region 窗口功能事件
        private void EventBinding()
        {
            KJ_FunStar.Click += KJ_Btn_Click;
            KJ_SaveBtn.Click += KJ_Btn_Click;
            KJ_SqlServerBtn.Click += KJ_Btn_Click;
            this.Shown += Form1_Shown;
            this.FormClosed += Form1_FormClosed;
            this.SizeChanged += Form1_SizeChanged;
            notifyIcon1.DoubleClick += NotifyIcon1_DoubleClick;
            _StarTimer.Tick += _StarTimer_Tick;

        }

        private void NotifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = true;  //显示在系统任务栏
                this.WindowState = FormWindowState.Normal;  //还原窗体
                notifyIcon1.Visible = false;  //托盘图标隐藏
            }
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)  //判断是否最小化
            {
                this.ShowInTaskbar = false;  //不显示在系统任务栏
                notifyIcon1.Visible = true;  //托盘图标可见
            }
        }

        /// <summary>
        /// 程序关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }
        /// <summary>
        /// 程序开始加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Shown(object sender, EventArgs e)
        {
            if (LoadAppConfig())
            {
                //开机启动
                if (KJ_SystemStar.Checked == true)
                {
                    KJ_Btn_Click(KJ_FunStar, null);
                }
            }
            else
            {
                MessageBox.Show("服务器配置错误！");
                SqlView frm = new SqlView();
                frm.ShowDialog();
            }
        }
        #endregion
        #region 运行事件
        /// <summary>
        /// 加载配置文件
        /// </summary>
        /// <returns></returns>
        private bool LoadAppConfig()
        {
            try
            {
                KJ_MachineID.Text = AppConfig.GetValue_Decrypt("MachineID");
                KJ_Interval.Text = AppConfig.GetValue_Decrypt("Interval");
                KJ_IPQianZui.Text = AppConfig.GetValue_Decrypt("IPQianZui");
                KJ_UserID.Text = AppConfig.GetValue_Decrypt("UserID");
                KJ_UserPwd.Text = AppConfig.GetValue_Decrypt("UserPwd");
                KJ_Port.Text = AppConfig.GetValue_Decrypt("Port");
                string fChecked = AppConfig.GetValue_Decrypt("SystemStar");
                if (fChecked.Length > 0)
                {
                    KJ_SystemStar.Checked = Convert.ToBoolean(fChecked);
                }
                SqlHelper._SqlConn = AppConfig.GetValue_Decrypt("SqlConn");
                if (SqlHelper._SqlConn.Length == 0)
                {
                    return false;
                }
                return true;
            }
            catch
            {
                MessageBox.Show("读取配置文件错误!");
                return false;
            }
        }
        /// <summary>
        /// 运行时间状态显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _StarTimer_Tick(object sender, EventArgs e)
        {
            TimeSpan ts = GetTimediff(_YunXinDtime, DateTime.Now);
            string txtDay = ts.Days.ToString();
            string txtHour = ts.Hours.ToString();
            string txtMin = ts.Minutes.ToString();
            string txtSec = ts.Seconds.ToString();
            label7.Text = txtDay + "天" + txtHour + "时" + txtMin + "分" + txtSec + "秒";
        }
        private TimeSpan GetTimediff(DateTime dt1, DateTime dt2)
        {
            return dt2 > dt1 ? dt2 - dt1 : dt1 - dt2;
        }
        #endregion
        #region 菜单功能事件
        private void KJ_Btn_Click(object sender, EventArgs e)
        {
            Button fButton = sender as Button;
            if ("开始监测" == fButton.Text)
            {
                StarFun();
            }
            else if ("停止监测" == fButton.Text)
            {
                _FTimer.Enabled = false;
                _StarTimer.Stop();

                label6.Text = "停止运行中……";
                label7.Text = "停止运行中……";
                KJ_FunStar.Text = "开始监测";

                KJ_MachineID.ReadOnly = false;
                KJ_Interval.ReadOnly = false;
                KJ_Port.ReadOnly = false;
                KJ_UserID.ReadOnly = false;
                KJ_UserPwd.ReadOnly = false;
                KJ_IPQianZui.ReadOnly = false;
                KJ_SystemStar.Enabled = true;
                KJ_SaveBtn.Enabled = true;
                KJ_SqlServerBtn.Enabled = true;
            }
            else if ("保存配置" == fButton.Text)
            {
                try
                {
                    if (KJ_MachineID.Text.Trim().Length > 0)
                    {
                        AppConfig.WriteValue_Encry(KJ_MachineID.Text.Trim(), "MachineID");
                    }
                    if (KJ_Interval.Value >= 0)
                    {
                        AppConfig.WriteValue_Encry(KJ_Interval.Value.ToString(), "Interval");
                    }
                    if (KJ_Port.Text.Trim().Length >= 0)
                    {
                        AppConfig.WriteValue_Encry(KJ_Port.Text.Trim(), "Port");
                    }
                    if (KJ_IPQianZui.Text.Trim().Length >= 0)
                    {
                        AppConfig.WriteValue_Encry(KJ_IPQianZui.Text.Trim(), "IPQianZui");
                    }
                    if (KJ_UserID.Text.Trim().Length >= 0)
                    {
                        AppConfig.WriteValue_Encry(KJ_UserID.Text.Trim(), "UserID");
                    }
                    if (KJ_UserPwd.Text.Trim().Length >= 0)
                    {
                        AppConfig.WriteValue_Encry(KJ_UserPwd.Text.Trim(), "UserPWD");
                    }
                    AppConfig.WriteValue_Encry(KJ_SystemStar.Checked.ToString(), "SystemStar");
                    if (KJ_SystemStar.Checked)
                    {
                        MessageBox.Show("设置开机自启动，需要修改注册表", "提示");
                        string path = Application.ExecutablePath;
                        RegistryKey rk = Registry.LocalMachine;
                        RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                        rk2.SetValue("ShengYueWorkShop", path);
                        rk2.Close();
                        rk.Close();
                    }
                    else
                    {
                        MessageBox.Show("取消开机自启动，需要修改注册表", "提示");
                        string path = Application.ExecutablePath;
                        RegistryKey rk = Registry.LocalMachine;
                        RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                        rk2.DeleteValue("ShengYueWorkShop", false);
                        rk2.Close();
                        rk.Close();
                    }
                    MessageBox.Show("保存成功");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            else if ("配置服务器" == fButton.Text)
            {
                SqlView frm = new SqlView();
                frm.ShowDialog();
            }

        }
        /// <summary>
        /// 开始监测
        /// </summary>
        private void StarFun()
        {
            if (KJ_MachineID.Text.Length == 0 || KJ_Interval.Value < 1)
            {
                MessageBox.Show(" 机台号不能为空 或者 监测间隔不能小于1分钟！");
            }
            if (KJ_IPQianZui.Text.Length == 0)
            {
                MessageBox.Show("IP地址段不能为空");
            }
            
            //先执行遍函数，判断是否正常运行；
            EventFun(null, null);

            _YunXinDtime = DateTime.Now;
            _StarTimer.Start();
            //间隔时间转换为毫秒
            double de = Convert.ToDouble(KJ_Interval.Value * 60 * 1000);
            //double de = Convert.ToDouble(numericUpDown1.Value * 60 * 1000);//测试时使用
            _FTimer = new System.Timers.Timer(de);//定时周期
            _FTimer.Elapsed += EventFun;//到了周期时执行清理事件
            _FTimer.AutoReset = true; //是否不断重复定时器操作
            _FTimer.Enabled = true; //定时器开始用
                                    //如果不写下面这句会有一个异常。
                                    //异常：线程间操作无效: 从不是创建控件"richtextbox"的线程访问它
                                    //但这不是最好的方法。如果只有一个进程调用richtextbox而已。就可以用下面这句
                                    //如果有多个线程调用richtextbox等控件。就要用委托。具体百度
                                    //一篇参考博客http://www.cnblogs.com/zyh-nhy/archive/2008/01/28/1056194.html
            Control.CheckForIllegalCrossThreadCalls = false;

            KJ_FunStar.Text = "停止监测";
            label6.Text = "程序正在运行中……";

            KJ_MachineID.ReadOnly = true;
            KJ_Interval.ReadOnly = true;
            KJ_Port.ReadOnly = true;
            KJ_UserID.ReadOnly = true;
            KJ_UserPwd.ReadOnly = true;
            KJ_IPQianZui.ReadOnly = true;
            KJ_SystemStar.Enabled = false;
            KJ_SaveBtn.Enabled = false;
            KJ_SqlServerBtn.Enabled = false;
        }
        private void EventFun(object sender, System.Timers.ElapsedEventArgs e)
        {
            //获取IP地址
            List<string> fIpList = new List<string>();
            fIpList = OtherFun.GetLocalIPAddress();
            foreach (string fIp in fIpList)
            {
                if (fIp.Contains(KJ_IPQianZui.Text))
                {
                    KJ_IP.Text = fIp;
                }
            }
            if (_DataModel != new BLL.DataModel.WS_FtpServer())
            {
                if (KJ_MachineID.Text.Trim() == _DataModel.MachineID && 
                    KJ_Port.Text.Trim() == _DataModel.ServerPort &&
                    KJ_IP.Text.Trim()== _DataModel.ServerIP &&
                    KJ_UserID.Text.Trim() == _DataModel.UID &&
                    KJ_UserPwd.Text.Trim() == _DataModel.PWD)
                {
                    //数据相同就不执行变更数据
                    return;
                }
            }
            _DataModel = new BLL.DataModel.WS_FtpServer();
            _DataModel.MachineID = KJ_MachineID.Text.Trim();
            _DataModel.ServerIP = KJ_IP.Text.Trim();
            _DataModel.ServerPort = KJ_Port.Text.Trim();
            _DataModel.UID = KJ_UserID.Text.Trim();
            _DataModel.PWD = KJ_UserPwd.Text.Trim();

            if (!_SqlHelper.UpdateServer(_DataModel))
            {
                //停止检测
                KJ_Btn_Click(null, null);
                label6.Text = "程序错误……";
            }
        }
        #endregion

    }
}
